package sistemadeproyectos;

import java.io.*;
import java.util.*;
import java.net.*;
import java.awt.Component;
import javax.swing.JOptionPane;
import javax.swing.ImageIcon;
import javax.swing.JTree;
import javax.swing.tree.*;
import javax.swing.tree.DefaultTreeCellRenderer;

/**
 * @author Antonio Mundo, 06-39956
 * @author Giancarlo Nebiolo, 06-39965
 * @author Angel Rubio, 06-40263
 * @version 1.6
 * 
 */
public class SeleccionaImagen extends javax.swing.JDialog {

    private Socket conexion;
    private ObjectInputStream entrada;
    private ObjectOutputStream salida;
    private Usuario usuarioActivo;
    private Equipo equipoActual;
    public String pathResultado;
    public ImageIcon imagenResultado;
    
    private int ocurrencias(String origen, String letra){
        int resultado = 0;
        for(int i = 0; i < origen.length(); i++){
            if((origen.charAt(i)+"").equals(letra)){
                resultado++;
            }
        }
        return resultado;
    }
    
    private String barra(){
        String resultado = "";
        if(System.getProperty("os.name").substring(0,5).equals("Windo")){
            resultado = "\\";
        }
        else if(System.getProperty("os.name").substring(0,5).equals("Linux")){
            resultado = "/";
        }
        return resultado;
    }
    
    /** Creates new form SeleccionaImagen */
    public SeleccionaImagen(java.awt.Frame parent, boolean modal, Equipo elEquipo, Usuario elUsuario) {
        super(parent, modal);
        initComponents();
        this.equipoActual = elEquipo;
        this.usuarioActivo = elUsuario;
        //Se prepara el modelo estructural del árbol
        DefaultMutableTreeNode raiz = new DefaultMutableTreeNode(elEquipo.getIdEquipo()+barra(), true);
        DefaultTreeModel modelo = new DefaultTreeModel(raiz);
        ServersConf rutas = new ServersConf();
        try {
            //Se crea la conexión con el serivor de Repositorio
            this.conexion = new Socket (rutas.getIPRepositorio(), rutas.getPuertoRepositorio());
            this.entrada = new ObjectInputStream ((this.conexion).getInputStream());
            this.salida = new ObjectOutputStream ((this.conexion).getOutputStream());
            this.salida.writeObject(this.usuarioActivo.getUsuario());
            this.salida.writeObject(this.equipoActual.getIdEquipo());
            //Se listan los archivos
            if(System.getProperty("os.name").substring(0,5).equals("Windo")){
                Inserta(raiz,1,1);
            }
            else if(System.getProperty("os.name").substring(0,5).equals("Linux")){
                Inserta(raiz,1,3);
            }
            jTree1.setModel(modelo);
            jTree1.setCellRenderer(new RendererArbol());
        }
        catch (IOException e) { 
            JOptionPane.showMessageDialog(this, "Error al establecer conexion con servidor.", 
                "Error en Conexion", JOptionPane.ERROR_MESSAGE);
            limpiar_socket();
            e.printStackTrace();
            this.dispose();
        }
    }
    
    private void Inserta(DefaultMutableTreeNode raiz, int nivel, int barrasBase){
        try{
            ArrayList<String> lista = (ArrayList<String>)(this.entrada).readObject();
            Iterator<String> it = lista.iterator();
            while(it.hasNext()){
                DefaultMutableTreeNode hoja = new DefaultMutableTreeNode(it.next());
                String textoHoja = (String)hoja.getUserObject();
                //Se filtra la lista de archivos, mostrando sólo los archivos con formatos de imagen
                if(textoHoja.length() > 3){
                    if(textoHoja.substring(textoHoja.length()-4,textoHoja.length()).equalsIgnoreCase(".jpg") ||
                            textoHoja.substring(textoHoja.length()-4,textoHoja.length()).equalsIgnoreCase(".jpeg") ||
                            textoHoja.substring(textoHoja.length()-4,textoHoja.length()).equalsIgnoreCase(".gif") ||
                            textoHoja.substring(textoHoja.length()-4,textoHoja.length()).equalsIgnoreCase(".png") ||
                            textoHoja.substring(textoHoja.length()-4,textoHoja.length()).equalsIgnoreCase(".bmp")){
                        //System.out.println("Agrega en nivel " + nivel + " " + textoHoja);
                        raiz.add(hoja);
                    }
                }
                //Se verifica si el elemento actual es una carpeta (directorio)
                if(textoHoja.substring(textoHoja.length()-1,textoHoja.length()).equals(barra())){
                    //System.out.println("Carpeta: " + textoHoja + " Recursion nivel " + nivel);
                    raiz.add(hoja);
                    int lim = textoHoja.lastIndexOf(barra());
                    textoHoja = textoHoja.substring(0, lim);
                    (this.salida).writeObject("carpetaActual");
                    String laCarpetaActual = (String)(this.entrada).readObject();
                    int lasOcurrencias = ocurrencias(laCarpetaActual, barra())-barrasBase;
                    //System.out.println("Recursion nivel " + nivel + ". Carpeta actual de repositorio: "+ laCarpetaActual + " con ocurrencias de barra " + lasOcurrencias);
                    while(lasOcurrencias > nivel){
                        (this.salida).writeObject("atras");
                        ArrayList<String> listaRetorno = (ArrayList<String>)(this.entrada).readObject();
                        (this.salida).writeObject("carpetaActual");
                        laCarpetaActual = (String)(this.entrada).readObject();
                        //System.out.println("REC dentro Hacia atras: Carpeta actual de repositorio: "+ laCarpetaActual);
                        lasOcurrencias--;
                    }
                    (this.salida).writeObject("abrir");
                    (this.salida).writeObject(textoHoja);
                    Inserta(hoja, nivel+1,barrasBase);
                }
            }
        }
        catch(IOException ioe){
            ioe.printStackTrace();
        }
        catch(ClassNotFoundException cnfe){
            cnfe.printStackTrace();
        }
    }
    
    private void limpiar_socket() {
        try { 
          (this.entrada).close();
          (this.salida).close();
          (this.conexion).close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTree1 = new javax.swing.JTree();
        jLabel1 = new javax.swing.JLabel();
        jlblImagen = new javax.swing.JLabel();
        jbtnAceptar = new javax.swing.JButton();
        jbtnCancelar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(sistemadeproyectos.SistemadeproyectosApp.class).getContext().getResourceMap(SeleccionaImagen.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTree1.setName("jTree1"); // NOI18N
        jTree1.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                jTree1ValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(jTree1);

        jLabel1.setName("jLabel1"); // NOI18N

        jlblImagen.setText(resourceMap.getString("jlblImagen.text")); // NOI18N
        jlblImagen.setName("jlblImagen"); // NOI18N

        jbtnAceptar.setText(resourceMap.getString("jbtnAceptar.text")); // NOI18N
        jbtnAceptar.setName("jbtnAceptar"); // NOI18N
        jbtnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnAceptarActionPerformed(evt);
            }
        });

        jbtnCancelar.setText(resourceMap.getString("jbtnCancelar.text")); // NOI18N
        jbtnCancelar.setName("jbtnCancelar"); // NOI18N
        jbtnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addGap(46, 46, 46)
                .addComponent(jlblImagen, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(36, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(337, Short.MAX_VALUE)
                .addComponent(jbtnAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(30, 30, 30)
                .addComponent(jbtnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(27, 27, 27))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap(93, Short.MAX_VALUE)
                        .addComponent(jLabel1)
                        .addGap(217, 217, 217))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(34, 34, 34)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, 0, 0, Short.MAX_VALUE)
                            .addComponent(jlblImagen, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 250, Short.MAX_VALUE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jbtnCancelar, javax.swing.GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE)
                    .addComponent(jbtnAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTree1ValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_jTree1ValueChanged
        // TODO add your handling code here:
        TreePath path = evt.getPath();
        Object [] nodos = path.getPath();
        String elPath = "";
        for (Object nodo: nodos){
            elPath = elPath + nodo.toString();
        }
        //System.out.println(elPath);
        if(!(elPath.substring(elPath.length()-1,elPath.length()).equals(barra()))){
            try{
                (this.salida).writeObject("imagen");
                (this.salida).writeObject(elPath);
                (this.salida).writeObject(jlblImagen.getWidth()+"");
                (this.salida).writeObject(jlblImagen.getHeight()+"");
                ImageIcon resultImagen = (ImageIcon)(this.entrada).readObject();
                jlblImagen.setIcon(resultImagen);
                this.pathResultado = elPath;
                this.imagenResultado = resultImagen;
            }
            catch(IOException ioe){
                ioe.printStackTrace();
            }
            catch(ClassNotFoundException cnfe){
                cnfe.printStackTrace();
            }
        }
    }//GEN-LAST:event_jTree1ValueChanged

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        // TODO add your handling code here:
        try{
            (this.salida).writeObject("salir");
        }
        catch(IOException ioe){}
        limpiar_socket();
        this.pathResultado = null;
        this.imagenResultado = null;
    }//GEN-LAST:event_formWindowClosing

    private void jbtnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnCancelarActionPerformed
        // TODO add your handling code here:
        try{
            (this.salida).writeObject("salir");
        }
        catch(IOException ioe){}
        limpiar_socket();
        this.pathResultado = null;
        this.imagenResultado = null;
        this.dispose();
    }//GEN-LAST:event_jbtnCancelarActionPerformed

    private void jbtnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnAceptarActionPerformed
        // TODO add your handling code here:
        try{
            (this.salida).writeObject("salir");
        }
        catch(IOException ioe){}
        limpiar_socket();
        this.dispose();
    }//GEN-LAST:event_jbtnAceptarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                //new SeleccionaImagen(null,null).setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTree jTree1;
    private javax.swing.JButton jbtnAceptar;
    private javax.swing.JButton jbtnCancelar;
    private javax.swing.JLabel jlblImagen;
    // End of variables declaration//GEN-END:variables
}

class RendererArbol extends DefaultTreeCellRenderer{
    
    ImageIcon imgJPG;
    ImageIcon imgGIF;
    ImageIcon imgPNG;
    ImageIcon imgBMP;

    private String pathImagen(String imagen){
        if(System.getProperty("os.name").substring(0,5).equals("Windo")){
            return System.getProperty("user.dir") + "\\src\\sistemadeproyectos\\images\\" + imagen;
        }
        else if(System.getProperty("os.name").substring(0,5).equals("Linux")){
           return System.getProperty("user.dir") + "/src/sistemadeproyectos/images/" + imagen;
        }
        else{
            return "";
        }
    }
    
    public RendererArbol() {
        this.imgJPG = new ImageIcon(pathImagen("imgJPG.jpg"));
        this.imgGIF = new ImageIcon(pathImagen("imgGIF.jpg"));
        this.imgPNG = new ImageIcon(pathImagen("imgPNG.jpg"));
        this.imgBMP = new ImageIcon(pathImagen("imgBMP.jpg"));
    }

    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus){
        super.getTreeCellRendererComponent(tree,value,selected,expanded,leaf,row,hasFocus);
        String val = value.toString();
        DefaultMutableTreeNode nodo = (DefaultMutableTreeNode)value;
        if(val.substring(val.length()-1,val.length()).equals("\\") == false){
            TreeNode t = (TreeNode)nodo;
            if(t!=null){
                String suTexto = t.toString();
                if(suTexto.length() > 3){
                    if(suTexto.substring(suTexto.length()-4,suTexto.length()).equalsIgnoreCase(".jpg") || suTexto.substring(suTexto.length()-4,suTexto.length()).equalsIgnoreCase(".jpeg")){
                        setIcon(imgJPG);
                        //System.out.println("JPG hallado: " + suTexto);
                    }
                    else if(suTexto.substring(suTexto.length()-4,suTexto.length()).equalsIgnoreCase(".gif")){
                        setIcon(imgGIF);
                        //System.out.println("GIF hallado: " + suTexto);
                    }
                    else if(suTexto.substring(suTexto.length()-4,suTexto.length()).equalsIgnoreCase(".png")){
                        setIcon(imgPNG);
                        //System.out.println("PNG hallado: " + suTexto);
                    }
                    else if(suTexto.substring(suTexto.length()-4,suTexto.length()).equalsIgnoreCase(".bmp")){
                        setIcon(imgBMP);
                        //System.out.println("BMP hallado: " + suTexto);
                    }
                }
            }
        }
        return this;
    }
}
